package com.cskaoyan.service;

import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserExample;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.vo.UserVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserVo query(Integer page, Integer limit,String sort, String order, String username, String mobile) {
        //分页和排序
        //页码、数据量
        /*PageHelper.startPage(page, limit); //mybatis在构建sql语句 👉 会构造limit和offset

        UserExample userExample = new UserExample();
        userExample.setOrderByClause(sort + " " + order);//${}做Sql拼接
        List<User> users = userMapper.selectByExample(userExample);

        //total != users.size();
        //total是满足条件的所有的数据量 👉 而不是当前的limit
        //可以通过PageInfo获得分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);//查询结果放进来
        long total = userPageInfo.getTotal();//总的数据量 👉 select count(*) 条件是byExample

        UserVo userVo = new UserVo();
        userVo.setItems(users);
        userVo.setTotal(total);*/
        PageHelper.startPage(page, limit);
        UserExample userExample = new UserExample();
        userExample.setOrderByClause(sort + " " + order);
        UserExample.Criteria criteria = userExample.createCriteria();
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (mobile != null && !"".equals(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        List<User> users = userMapper.selectByExample(userExample);

        /*UserExample userExample2 = new UserExample();
        userExample2.setOrderByClause(sort + " " + order);
        userExample2.createCriteria().andUsernameLike("%" + username + "%").andMobileEqualTo(mobile);*/
        PageInfo<User> userPageInfo = new PageInfo<User>(users);
        long total = userPageInfo.getTotal(); //select count(*)
        UserVo userVo = new UserVo();
        userVo.setItems(users);
        userVo.setTotal(total);
        return userVo;
    }
}
